<?php
class UsersController extends AppController {

	var $name = 'Users';
	
	function index() {
		$this->User->recursive = 2;
		$this->set('users', $this->paginate());

		
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}
	
	function login(){	
		if($this->Auth->user()) $this->redirect(array('controller'=>'links','action'=>'index'));
		
		if($this->data){
			$this->data['User']['email']=$this->data['User']['email'];
			
			// little trick in case a user put the login name instead of the mail
			if(!strpos($this->data['User']['email'],'@')){
				$this->data['User']['email']=$this->User->field('email',array('login'=>$this->data['User']['email']));
			}

			if($this->Auth->login($this->data)){
				$this->redirect(array('controller'=>'links','action'=>'index'));
			}
		}
	}

	function logout(){
		$this->Cookie->destroy('User');
		$this->redirect($this->Auth->logout());
	}

	function register(){
		if ($this->data) {
						
			$this->User->validate['password']['isConfirmed']= array(
        		'rule' => array('equalTo', $this->Auth->password($this->data['User']['passwordconfirmation'])),  
        		'message' => 'La confirmacion del password no coincide'
        	);
       	   	
    		$this->data['User']['ip']=Configure::read('visitor_ip');
        	            	
        	$this->User->create($this->data);
        	if($this->User->save(null,true,array('login','level','ip','password','email'))){
        		//@todo enviar confirmacion al usuario
        		//$this->redirect(array('controller'=>'pages','action'=>'display','user_pending'));
        	}
        	        	
        	$this->data['User']['password']=$this->data['User']['passwordconfirmation']='';
    	}
	}
	

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The user has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for user', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->delete($id)) {
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('User was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
?>